package com.ming.study.redis.controller;

import com.ming.study.redis.dto.HashDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/hash")
@Slf4j
public class HashController {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @RequestMapping("/put")
    public String setHash(@RequestBody HashDto request){
        try {
            HashOperations<Object, Object, Object> hashOperations = redisTemplate.opsForHash();
            hashOperations.putAll(request.getKey(), request.getHashMap());
        }catch (Exception e){
            log.error(e.toString());
            return e.toString();
        }
        return "success";
    }

    @RequestMapping("/get")
    public HashDto getHash(@RequestBody HashDto request){
        HashDto hashDto = new HashDto();
        try {
            HashOperations<Object, Object, Object> hashOperations = redisTemplate.opsForHash();
            Map<Object, Object> map = hashOperations.entries(request.getKey());
            hashDto.setHashMap(map);
        }catch (Exception e){
            log.error(e.toString());
        }
        return hashDto;
    }
}
